/**
 * This Class speaks with the football API
 */
var http = require('http');
var fs = require('fs');
var xmlUtils = require('./xmlUtils.js');
var key = "fj3uewugve9ax9j6g4d7cph9";

/***
 * Gets the schedule from the API and saves to resources/schedule.xml
 */
var getSchedule = function(callback) {
    var totalPath = "http://api.sportsdatallc.org/soccer-t2/wc/matches/schedule.xml?api_key=" + key;
    var gsaReq = http.get(totalPath, function(response) {
        var completeResponse = '';
        response.on('data', function(chunk) {
            completeResponse += chunk;
        });
        response.on('end', function() {
            console.log("Completed Reading XML Schedule File");

            fs.writeFile(__dirname + "/resources/schedule.xml", completeResponse, function(err) {
                if (err) {
                    console.log(err);
                    callback(false);

                } else {
                    console.log("The file was saved!");
                    callback(true);

                }
            });

        });
    });

};
/**
 * Asks the xmlUtils to parse the schedule and return only matches that are in this date
 * @param date object
 * @return callback of an array of {match_id : <value>, date:<value>}
 * No need to get a new schedule, use the one in the resources
 */
var listMatchesByDate = function(i_date, callback) {
    xmlUtils.getMatchesByDate(__dirname + "/resources/schedule.xml", i_date, function(result) {
        callback(result);
    });
};

/**
 * @return result is a object {match_id: value , date: value , home: value , away: value}
 */
var getMatchInfo = function(match_id, callback) {
    xmlUtils.getMatchFromSchedById(__dirname + "/resources/schedule.xml", match_id, function(result) {
        callback(result);
    });
};

/**
 * @return result is a object {match_id: value , score: [home,away] , home: value , away: value , winner: value}
 */
var getMatchSummary = function(match_id, callback) {

    /** Commented for testing purposes**/

    var totalPath = "http://api.sportsdatallc.org/soccer-t2/wc/matches/" + match_id + "/boxscore.xml?api_key=" + key;
    var gsaReq = http.get(totalPath, function(response) {
        var completeResponse = '';
        response.on('data', function(chunk) {
            completeResponse += chunk;
        });
        response.on('end', function() {
            console.log("Completed Reading XML Boxscore for match - " + match_id);
            var filePath = __dirname + "/resources/" + match_id + ".xml";
            fs.writeFile(filePath, completeResponse, function(err) {
                if (err) {

                    callback(false);
                } else {
                    xmlUtils.getMatchBoxscore(filePath, function(result) {

                        callback(result);

                    });

                }
            });

        });
    });

};

/***
 * Gets the schedule from the API and saves to resources/schedule.xml
 */
var getStandings = function(callback) {
    var totalPath = "http://api.sportsdatallc.org/soccer-t2/wc/teams/standing.xml?api_key=" + key;
    var gsaReq = http.get(totalPath, function(response) {
        var completeResponse = '';
        response.on('data', function(chunk) {
            completeResponse += chunk;
        });
        response.on('end', function() {
            console.log("Completed Reading XML Standings File");
            fs.writeFile(__dirname + "/resources/standing.xml", completeResponse, function(err) {
                if (err) {

                    callback(false);
                } else {
                    callback(true);
                }
            });

        });
    });
};
//getStandings();

/***
 * Gets the schedule from the API and saves to resources/schedule.xml
 */
var getHierarchy = function(callback) {
    var totalPath = "http://api.sportsdatallc.org/soccer-t2/wc/teams/hierarchy.xml?api_key=" + key;
    var gsaReq = http.get(totalPath, function(response) {
        var completeResponse = '';
        response.on('data', function(chunk) {
            completeResponse += chunk;
        });
        response.on('end', function() {
            console.log("Completed Reading XML hierarchy File");
            fs.writeFile(__dirname + "/resources/hierarchy.xml", completeResponse, function(err) {
                if (err) {

                    callback(false);
                } else {
                    callback(true);
                }
            });

        });
    });
};

var getAllTeams = function(callback) {
    var totalPath = "http://api.sportsdatallc.org/soccer-t2/wc/teams/hierarchy.xml?api_key=" + key;
    var gsaReq = http.get(totalPath, function(response) {
        var completeResponse = '';
        response.on('data', function(chunk) {
            completeResponse += chunk;
        });
        response.on('end', function() {
            console.log("Completed Reading XML Standings File");
            fs.writeFile(__dirname + "/resources/hierarchy.xml", completeResponse, function(err) {
                if (err) {
                    console.log(err);
                } else {
                    console.log("The file was saved!");
                    //Call the xmlUtils getTeams()
                    callback(null);
                }
            });

        });
    });

};

/**
 * After a team has won a game - this finds out what match_id the team is going to, gets an updated schedule, and
 * @param team_id
 * @return callback with the match {team_name:<value> , match_id:<value> , home:<true/false>}
 */
var getNextStep = function(team_name, i_levelToGet, callback) {
    getSchedule(function(result) {
        if (result) {
            //Schedule.xml has been saved
            xmlUtils.getNextMatchByTeamName(__dirname + "/resources/schedule.xml", team_name, i_levelToGet, function(matchObject) {
                callback(matchObject);
            });
        } else {
            //Parser fail
            console.log("error");
            callback(null);
        }
    });
};

/**
 * Sends it to xmlUtils.mapMatchesByLevel
 */
var getMappingByLevel = function(i_level, callback) {
    xmlUtils.getMapMatchesByLevel(__dirname + "/resources/schedule.xml", parseInt(i_level), function(result) {
        callback(result);
    });
};

/**
 * Returns the mappings of all the qualifiers between GroupName and the teams
 */
var getAllQualifiersMapping = function(callback) {
    getHierarchy(function(result) {
        if (result) {
            //Successful in calling the API
            console.log("footballAPI - Parsing the new qualifiers mapping");
            xmlUtils.mapQualifiersFromHierarchy(__dirname + "/resources/hierarchy.xml", function(parsedResult) {
                callback(parsedResult);
            });

        }
    });
};

/**
 * calls the API and get the latest standings (getStandings())
 * then calls xmlUtils to parse the standings
 * put in on the callback
 * @param {Object} groupName
 * @param {Object} callback
 */
var getQualifiers = function(groupName, callback) {

    // xmlUtils.getQualifiersFromStanding(__dirname + "/resources/standing.xml", groupName, function(groupObject) {
    // //the qualifiers for this table have been parsed {groupName:<value>  , rankedFirst:<team_name> , rankedSecond:<teamName>}
    //
    // callback(groupObject);
    // });

    getStandings(function(result) {
        if (result == false) {
            //Couldn't pull standings
            callback(null);

        } else {
            //Standings were saved in resources
            xmlUtils.getQualifiersFromStanding(__dirname + "/resources/standing.xml", groupName, function(groupObject) {
                //the qualifiers for this table have been parsed {groupName:<value>  , rankedFirst:<team_name> , rankedSecond:<teamName>}
                callback(groupObject);
            });

        }
    });

};

var allGroupMatches = null;
var getAllGroupMatches = function(callback) {
    if (allGroupMatches == null) {
        console.log("No Previous Group Matches");
        syncGroupMatches(function(result) {
            callback(result);
        });
    } else {
        callback(allGroupMatches);
    }
};

var syncGroupMatches = function(callback) {
    xmlUtils.getGroupMatches(__dirname + "/resources/schedule.xml", function(result) {
        allGroupMatches = result;
        callback(result);
    });

};
var allKnockoutMatches = null;
var getAllKnockoutMatches = function(callback) {
    if (allKnockoutMatches == null) {
        console.log("No Previous Knockout Matches");
        syncKnockoutMatches(function(result) {
            allKnockoutMatches = result;
            callback(result);
        });
    } else {
        callback(allKnockoutMatches);
    }
};

var syncKnockoutMatches = function(callback) {
    xmlUtils.getKnockoutMatches(__dirname + "/resources/schedule.xml", function(result) {
        callback(result);
    });
};

/** TESTING ONLY**/

var demoArray = [{
    match_id : "8b2154a5-d837-451b-a7f1-8cf06cfaa2ff",
    winner : "Brazil"
}, {
    match_id : "d4f14940-be18-4d2d-8464-b0fea10f2e79",
    winner : "Mexico"
}, {
    match_id : "03702fc0-6f31-4b66-aeef-ffff98cc033b",
    winner : "Spain"
}, {
    match_id : "af79d0ae-ff8f-46a8-ae6f-08cdb16d8cd0",
    winner : "Chile"
}, {
    match_id : "191cc03e-4e54-4f43-8de7-9e90d50b4d17",
    winner : "Greece"
}, {
    match_id : "c4d7aece-bfdb-4c2d-a821-fbb38210fbaf",
    winner : "Costa Rica"
}, {
    match_id : "cf413059-955b-4470-b368-b24407e7c019",
    winner : "Italy"
}, {
    match_id : "dbe1746f-6275-41f8-afff-f293e4baa277",
    winner : "Japan"
}, {
    match_id : "9613c694-9001-4448-872f-d5a02cb44137",
    winner : "Ecuador"
}, {
    match_id : "98135852-fb73-4551-8856-fa0fac50182c",
    winner : "France"
}, {
    match_id : "25ecdac9-453a-4057-9858-fe214e10a391",
    winner : "Argentina"
}, {
    match_id : "33f6fb10-e9d7-4904-8940-7f7f01b60d21",
    winner : "Germany"
}, {
    match_id : "45ecc96a-01ed-4cee-a138-81f2b9573a0b",
    winner : "Iran"
}, {
    match_id : "0e3ca2d9-6285-45e5-a1da-f3ce1a77d80a",
    winner : "Ghana"
}, {
    match_id : "6679d81b-5056-4fe7-9e7d-96afc9b608d8",
    winner : "Belgium"
}, {
    match_id : "839afcad-8196-4862-8ae1-495a8f2e351e",
    winner : "Brazil"
}, {
    match_id : "06422ac7-f6a5-4ed5-ab00-417c4902665c",
    winner : "Brazil"
}, {
    match_id : "1b595125-220f-4619-aad2-d1d0659a84f1",
    winner : "Brazil"
}, {
    match_id : "bc377b5a-2940-4651-a7f1-ddac74d0be5a",
    winner : "Brazil"
}, {
    match_id : "1f0adb6d-83ce-4606-a203-3881183024a0",
    winner : "Brazil"
}, {
    match_id : "457c04a5-ce7c-4429-8d51-59ae1d237eb1",
    winner : "Brazil"
}, {
    match_id : "6a0c97db-8c26-43fa-b146-2277afe5cc1e",
    winner : "Brazil"
}, {
    match_id : "3b9ccb92-eeb7-48b6-b3c3-712dfaa2d970",
    winner : "Brazil"
}, {
    match_id : "09c306c1-075c-443b-8422-846f7fce00d1",
    winner : "Brazil"
}, {
    match_id : "3a447e9d-bfe0-4d25-b788-78a9099d9c2c",
    winner : "Brazil"
}, {
    match_id : "561b07a5-0597-4dfb-a3f2-ee027341c7db",
    winner : "Brazil"
}, {
    match_id : "915db875-3167-453b-88a7-49e09af91e2b",
    winner : "Brazil"
}, {
    match_id : "569d6be7-68a7-4332-a10e-b48842e6a65d",
    winner : "Brazil"
}, {
    match_id : "1b7f9a66-1ac3-426d-b2b1-410b0103d34b",
    winner : "Brazil"
}, {
    match_id : "8f7484e2-ddea-4a26-91c2-f1a5a35d05cb",
    winner : "Brazil"
}, {
    match_id : "3c65639a-4fc0-4d60-9917-97d263a7dd61",
    winner : "Brazil"
}, {
    match_id : "8e2deeae-e858-4a3c-b1df-cb8f90ffb743",
    winner : "Brazil"
}, {
    match_id : "19666fae-210c-4fe0-8c15-632ad763bedf",
    winner : "Brazil"
}, {
    match_id : "379510f1-98fd-4402-93f5-5ce4791122f8",
    winner : "Brazil"
}, {
    match_id : "dc7425cf-73b1-411e-82dd-1b79c0b003f1",
    winner : "Brazil"
}, {
    match_id : "6f0fba5f-ac4f-4076-a0be-7bcd1cfd4897",
    winner : "Brazil"
}, {
    match_id : "7c9e28c1-a383-42c9-9f42-75247cb4d0bf",
    winner : "Brazil"
}, {
    match_id : "ed14e4da-7f06-4b18-84df-5e92f599c28a",
    winner : "Brazil"
}, {
    match_id : "947b56b8-8cef-441a-9788-cbd543f9651a",
    winner : "Brazil"
}, {
    match_id : "1f6a203e-35e1-4b5d-83a1-62eaaec30f1e",
    winner : "Brazil"
}, {
    match_id : "dc9583c4-da5f-4d39-bfbe-aa71a50564a5",
    winner : "Brazil"
}, {
    match_id : "21de3e84-9956-4ebf-98ae-22f40cf245a0",
    winner : "Brazil"
}, {
    match_id : "9a6bb503-32d1-4a20-9061-c52af97b6838",
    winner : "Brazil"
}, {
    match_id : "5a897135-5ea8-4939-a6d9-c408d366f31f",
    winner : "Brazil"
}, {
    match_id : "547c9036-93b3-418c-8f82-bc48244701d0",
    winner : "Brazil"
}, {
    match_id : "c3cadf94-429b-44bf-927c-e7d76ade548c",
    winner : "Brazil"
}, {
    match_id : "836943d5-1798-4bbc-960a-b695acce0040",
    winner : "Brazil"
}, {
    match_id : "9ccf78a3-5c63-40d3-b618-007952b52738",
    winner : "Brazil",
    level : 4
}, {
    match_id : "364f95a0-3d91-4b59-91df-554075bb18b9",
    winner : "Greece",
    level : 4
}, {
    match_id : "2339574a-5064-4384-9ff5-5f76dca518a8",
    winner : "Spain",
    level : 4
}, {
    match_id : "c3023920-3391-46a5-86ff-07557542b967",
    winner : "England",
    level : 4
}, {
    match_id : "29d2c31a-bda2-46cd-bc43-9e445280aa4d",
    winner : "France",
    level : 4
}, {
    match_id : "e04c7f31-d868-4782-8eb1-ca962bf66aa4",
    winner : "USA",
    level : 4
}, {
    match_id : "6d0589e4-694e-4aba-b36c-f193df8c00a8",
    winner : "Argentina",
    level : 4
}, {
    match_id : "76ea9597-7cd1-4861-be27-e6c5f0b6612e",
    winner : "Russia",
    level : 4
}, {
    match_id : "5834846e-ed52-4a3a-aeba-e346a7c2060b",
    winner : "Brazil",
    level : 3
}, {
    match_id : "644d6686-6b41-4bf4-822f-43fd5f6b5dfc",
    winner : "Spain",
    level : 3
}, {
    match_id : "ea1e025c-1fcf-47f4-a782-70e4e791f338",
    winner : "France",
    level : 3
}, {
    match_id : "2711d14d-f2ea-4751-a400-6cdbd9b61b5e",
    winner : "Argentina",
    level : 3
}, {
    match_id : "9403f149-fd67-4590-9b1b-2de4cf70dcce",
    winner : "Brazil",
    level : 2
}, {
    match_id : "ae54d136-d119-429f-9a02-79854d68510b",
    winner : "Argentina",
    level : 2
}, {
    match_id : "22653ed5-0b2c-4e30-b10c-c6d51619b52b",
    winner : "Brazil",
    level : 1
}];

function demoFindWinner(match_id) {
    for (var i = 0; i < demoArray.length; i++) {
        if (demoArray[i].match_id == match_id) {
            return demoArray[i].winner;
        }

    };
}

function demoFindLevel(match_id) {
    for (var i = 0; i < demoArray.length; i++) {
        if (demoArray[i].match_id == match_id) {
            return demoArray[i].level;
        }

    };
}

exports.getAllTeams = getAllTeams;
exports.getStandings = getStandings;
exports.getSchedule = getSchedule;
exports.syncGroupMatches = syncGroupMatches;
exports.getAllGroupMatches = getAllGroupMatches;
exports.getAllKnockoutMatches = getAllKnockoutMatches;
exports.syncKnockoutMatches = syncKnockoutMatches;
exports.getMatchSummary = getMatchSummary;
exports.getMatchInfo = getMatchInfo;
exports.getQualifiers = getQualifiers;
exports.getNextStep = getNextStep;
exports.getMappingByLevel = getMappingByLevel;
exports.getAllQualifiersMapping = getAllQualifiersMapping;
exports.listMatchesByDate = listMatchesByDate;
